//
//  ONEChatChatViewController.m
//  ONEChat
//
//  Created by 楼楚 on 15/12/24.
//  Copyright © 2015年 Chu Lou. All rights reserved.
//

#import "ONEChatChatViewController.h"
#import "UIImageView+WebCache.h"
#import "UIImage+Scale.h"
#import "ONEChatMsgCell.h"
#import "ONEChatRecordTool.h"
//尺寸
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define WIDTH  [UIScreen mainScreen].bounds.size.width
#define ChatHeight 45.0


@interface ONEChatChatViewController ()<UITableViewDelegate,UITableViewDataSource,NSFetchedResultsControllerDelegate,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    NSFetchedResultsController *_resultContr;
    UIImagePickerController    *_picker;
    float _sendBackViewHeight;
    float _sendTextViewHeight;
}

@property(nonatomic,strong) UITableView  *tableView;
@property(nonatomic,strong) UIView       *sendMsgView;
@property(nonatomic,strong) UIView       *recordMsgView;
@property(nonatomic,strong) UITextView   *sendTextView;
@property(nonatomic,strong) UIButton     *sendButton;

@end
@implementation ONEChatChatViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupView];
//    增加通知-键盘
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleKeyBoardDidShow:) name:UIKeyboardWillShowNotification   object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [self loadMsgs];
    [self scrollToTableBottom];
}
#pragma mark - 铺界面
- (void) setupView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-ChatHeight)];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:self.tableView];
    
    self.sendMsgView = [[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT - ChatHeight, WIDTH, ChatHeight)];
    self.sendMsgView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    [self.view addSubview:self.sendMsgView];
    self.sendTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 5, WIDTH - 10 - 90, 35)];
    self.sendTextView.returnKeyType = UIReturnKeySend;
    self.sendTextView.font = [UIFont systemFontOfSize:17];
    self.sendTextView.editable = YES;
    self.sendTextView.delegate = self;
    [self.sendMsgView addSubview:self.sendTextView];
    
    UIButton * addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    addButton.frame = CGRectMake(WIDTH - 85, 2, 37, 37);
    [addButton addTarget:self action:@selector(addNextImage) forControlEvents:UIControlEventTouchUpInside];
    [self.sendMsgView addSubview:addButton];
    
    self.sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendButton.frame = CGRectMake(WIDTH - 45, 5, 40, 30);
    [self.sendButton setImage:[UIImage imageNamed:@"record.png"] forState:UIControlStateNormal];
    [self.sendButton addTarget:self action:@selector(buildRecordView) forControlEvents:UIControlEventTouchUpInside];
    [self.sendMsgView addSubview:self.sendButton];
}
#pragma mark - 按下录音按钮时的界面
- (void)buildRecordView{
    self.recordMsgView = [[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT - ChatHeight, WIDTH, ChatHeight)];
    self.recordMsgView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    [self.view addSubview:self.recordMsgView];
    
    UILabel *recordLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, WIDTH - 10 - 90, 35)];
    
    recordLabel.backgroundColor = [[UIColor blueColor]colorWithAlphaComponent:0.3f];
    recordLabel.text = @"长按录音开始···";
    recordLabel.tag = 1001;
    recordLabel.textAlignment = NSTextAlignmentCenter;
    recordLabel.userInteractionEnabled = YES;
    
    [self.recordMsgView addSubview:recordLabel];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    backBtn.backgroundColor = [UIColor blackColor];
    [backBtn setTitle:@"back" forState:(UIControlStateNormal)];
    [backBtn setTitleColor:[[UIColor blueColor]colorWithAlphaComponent:0.7f] forState:UIControlStateNormal];
    
    backBtn.frame = CGRectMake(WIDTH-85, 5, 70, 35);
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.recordMsgView addSubview:backBtn];
    
    UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressNextDo:)];
    [recordLabel addGestureRecognizer:longPress];

}
- (void)longPressNextDo:(UILongPressGestureRecognizer * )longPress
{
    if(longPress.state == UIGestureRecognizerStateBegan)
    {
        NSLog(@"begin");
        UILabel * label = (UILabel *)[self.recordMsgView viewWithTag:1001];
        label.text = @"录音正在进行中···";
        label.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.3f];
        
        [self startRecord];
    }
    if(longPress.state == UIGestureRecognizerStateEnded)
    {
        [self stopRecord];
        [self.recordMsgView removeFromSuperview];
//        [self  sendAsStream];
        NSLog(@"stop");
        
    }
}
#pragma mark - ******************** 录音方法
- (void)startRecord {
    NSLog(@"开始录音");
    [[ONEChatRecordTool sharedRecorder] startRecord];
}

- (void)stopRecord {
    NSLog(@"停止录音");
    [[ONEChatRecordTool sharedRecorder] stopRecordSuccess:^(NSURL *url, NSTimeInterval time) {
        
        // 发送声音数据
        NSData *data = [NSData dataWithContentsOfURL:url];
        [self sendMessageWithData:data bodyName:[NSString stringWithFormat:@"audio:%.1f秒", time]];
        
    } andFailed:^{
        
        [[[UIAlertView alloc] initWithTitle:@"提示" message:@"时间太短" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    }];
}


#pragma mark - 发送图片
#pragma mark - 图片的传输
- (void)addNextImage
{
    UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相机",@"相册", nil];
    [chooseImageSheet showInView:self.view];
}
#pragma mark - 图片代理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    _picker = [[UIImagePickerController alloc] init];
    _picker.delegate = self;
    
    switch (buttonIndex) {
        case 0://Take picture
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                
                _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            }
            
            [self presentViewController:_picker animated:NO completion:nil];
    
            break;
            
        case 1:
            //From album
            _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            [self presentViewController:_picker animated:NO completion:^{
                
                // 改变状态栏的颜色  为正常  这是这个独有的地方需要处理的
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
            }];
            break;
            
        default:
            
            break;
    }
}
#pragma mark - 图片的传输
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        [self sendMessageWithData:data bodyName:@"image"];
        
        [self dismissViewControllerAnimated:YES completion:nil];
   }
}
#pragma mark - 将图片转化成二进制文件并发送
//TODO 需要更快一点的方法 这个太慢了
- (void)sendMessageWithData:(NSData *)data bodyName:(NSString *)name
{
     XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.friendjid];
    
    [message addBody:name];
    
    // 转换成base64的编码
    NSString *base64str = [data base64EncodedStringWithOptions:0];
    
    // 设置节点内容
    XMPPElement *attachment = [XMPPElement elementWithName:@"attachment" stringValue:base64str];
    
    // 包含子节点
    [message addChild:attachment];
    
    // 发送消息
    [[ONEChatXMPPTool sharedONEChatXMPPTool].xmppStream sendElement:message];
}

#pragma mark - 加载XMPPMessageArchiving数据库的数据显示在表格
-(void)loadMsgs
{
    NSManagedObjectContext *context = [ONEChatXMPPTool sharedONEChatXMPPTool].msgStorge.mainThreadManagedObjectContext;
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",[ONEChatUserInfo sharedONEChatUserInfo].jid,self.friendjid.bare];
    request.predicate = pre;
    
    NSSortDescriptor *timeSort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    
    request.sortDescriptors = @[timeSort];
    
    _resultContr = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    
    NSError *err = nil;
    [_resultContr performFetch:&err];
    _resultContr.delegate = self;
    if (err) {
        NSLog(@"%@",err);
    }
}
#pragma mark - 表格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    XMPPMessageArchiving_Message_CoreDataObject *msg = _resultContr.fetchedObjects[indexPath.row];
    if ([msg.body isEqualToString:@"image"]) {
        
            return 300 + 10;
        
         }else{
            CGSize size = [msg.body boundingRectWithSize:CGSizeMake(250, 1000) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:14]} context:nil].size;
            return size.height + 10 + 20;
        }
//    return 100;
}

#pragma mark - 表格的数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _resultContr.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID =@"ChatCell";
    ONEChatMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil)
    {
        cell = [[ONEChatMsgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // 让后面选中的没有阴影效果
        
    }
    
    XMPPMessageArchiving_Message_CoreDataObject *msg = _resultContr.fetchedObjects[indexPath.row];
//    取出文本消息 设定字号 获取行数
    CGSize size = [msg.body boundingRectWithSize:CGSizeMake(250, 1000) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  attributes:@{NSFontAttributeName :[UIFont systemFontOfSize:14]} context:nil].size;
    //布置头像位置
    cell.rightAvatarView.frame = CGRectMake(WIDTH - 35, 5, 30, 30);
    cell.leftAvatarView.frame = CGRectMake(5, 5, 30, 30);
    
//    NSString *path = [msg.message pathForAttachment:self.friendjid.bare timestamp:message.timestamp];
    
    if ([msg.outgoing boolValue]) {
//自己的
        cell.leftAvatarView.hidden = YES;
        cell.leftImgView.hidden = YES;
        cell.leftChatView.hidden = YES;
        cell.leftVideoBtn.hidden = YES;
        cell.rightAvatarView.hidden = NO;
        if ([msg.body isEqualToString:@"image"]) {
        //  图片
            cell.rightImgView.hidden = NO;
            cell.rightChatView.hidden = YES;
            cell.rightVideoBtn.hidden = YES;
            
            XMPPMessage *imageMsg = msg.message;
            
            for (XMPPElement *node in imageMsg.children) {
                // 取出消息的解码
                NSString *base64str = node.stringValue;
                NSData *data = [[NSData alloc]initWithBase64EncodedString:base64str options:0];
                UIImage *image = [[UIImage alloc]initWithData:data];
                cell.rightImgView.frame = CGRectMake(WIDTH - 40 - 300, 5,300, 300);
                cell.rightImgView.image = image;
               
                [self.view endEditing:YES];
            }
            
        }else if ([msg.body hasPrefix:@"audio"]){
             //语音
            cell.rightImgView.hidden = YES;
            cell.rightChatView.hidden = YES;
            cell.rightVideoBtn.hidden = NO;
            NSString *newstr = [msg.body substringFromIndex:6];
        
            NSString *youStr = [NSString stringWithFormat:@"%@点我点我点☜=(゜ω゜)",newstr];
            [cell.rightVideoBtn setTitle:youStr forState:UIControlStateNormal];
            [cell.rightVideoBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [cell.rightVideoBtn addTarget:self action:@selector(cellSelectIndex:) forControlEvents:UIControlEventTouchUpInside];
            //            cell.audioPath = path;
//            cell.audioPath = path;
            
        }else {
        //    文字
            cell.rightImgView.hidden = YES;
            cell.rightChatView.hidden = NO;
            cell.rightVideoBtn.hidden = YES;
            cell.rightTextLabel.frame = CGRectMake(10, 5, size.width, size.height);
            cell.rightChatView.frame = CGRectMake(WIDTH - 40 - size.width -25, 5, size.width + 25, size.height +25);
            cell.rightTextLabel.text = msg.body;
            
        }
    } else {
//别人发的
        cell.rightAvatarView.hidden = YES;
        cell.rightImgView.hidden = YES;
        cell.rightChatView.hidden = YES;
        cell.rightVideoBtn.hidden = YES;
        cell.leftAvatarView.hidden = NO;
        if ([msg.body isEqualToString:@"image"]) {
         //图片
            cell.leftImgView.hidden = NO;
            cell.leftChatView.hidden = YES;
            cell.leftVideoBtn.hidden = YES;
            XMPPMessage *imageMsg = msg.message;
            
            for (XMPPElement *node in imageMsg.children) {
                // 取出消息的解码
                NSString *base64str = node.stringValue;
                NSData *data = [[NSData alloc]initWithBase64EncodedString:base64str options:0];
                UIImage *image = [[UIImage alloc]initWithData:data];
                cell.leftImgView.frame = CGRectMake(40, 5, 300, 300);
                cell.leftImgView.image = image;
//
                [self.view endEditing:YES];
            }

            
        } else if ([msg.body hasPrefix:@"audio"]){
        //语音
            cell.leftImgView.hidden = YES;
            cell.leftChatView.hidden = YES;
            cell.leftVideoBtn.hidden = NO;
            NSString *newstr = [msg.body substringFromIndex:6];
            NSString *youStr = [NSString stringWithFormat:@"(゜ω゜)=☞点TA点TA点%@",newstr];
            [cell.leftVideoBtn setTitle:youStr forState:UIControlStateNormal];
            [cell.leftVideoBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [cell.leftVideoBtn addTarget:self action:@selector(cellSelectIndex:) forControlEvents:UIControlEventTouchUpInside];
            //            cell.audioPath = path;
            
        }else {
         //文字
            cell.leftImgView.hidden = YES;
            cell.leftChatView.hidden = NO;
            cell.leftVideoBtn.hidden = YES;
            cell.leftTextLabel.frame = CGRectMake(10, 5, size.width, size.height);
            cell.leftChatView.frame = CGRectMake(45, 5, size.width + 25, size.height +25);
            cell.leftTextLabel.text = msg.body;
        }
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    XMPPMessageArchiving_Message_CoreDataObject *msg = _resultContr.fetchedObjects[indexPath.row];
    if([msg.body hasPrefix:@"audio"])
    {
        
        NSLog(@"realy play");
        //        [self makeVideoPlayer:[self getVideoStremData]];
//        [self makeVideoPlayer:chatIden.recordData];
    }
    
}
//- (void)cellSelectIndex:(UIButton *)cellBtn
//{
//    
////    ChatItem *chatIden = [self.datasource objectAtIndex:cellBtn.tag - 300];
//     XMPPMessageArchiving_Message_CoreDataObject *msg = [_resultContr.fetchedObjects objectAtIndex:cellBtn.tag - 300];
//    if([msg.body hasPrefix:@"audio"])
//    {
//        }
//}

#pragma mark -ResultsController代理
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
    [self scrollToTableBottom];
}
#pragma mark - textview代理
- (void)textViewDidChange:(UITextView *)textView
{
    // 根据输入内容改变其高度
    float textHeight = [self heightForString:textView.text fontSize:16 andWidth:textView.frame.size.width];
    _sendTextViewHeight = textHeight;
     self.sendTextView.frame = CGRectMake(10, 5, WIDTH - 10 - 90, _sendTextViewHeight);
    self.sendMsgView.frame = CGRectMake(0, HEIGHT -  _sendBackViewHeight - _sendTextViewHeight - 10, WIDTH, _sendTextViewHeight + 10);
    NSString *text = textView.text;
    // 换行==send
    if ([text rangeOfString:@"\n"].length != 0) {
        text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        [self sendMsgsWithText:text bodyType:@"text"];
        // 发送完之后清空textView数据，恢复原样
        textView.text = nil;
        //  发送完消息 把textview的高度改回来
        [self.sendTextView resignFirstResponder];
        self.tableView.frame = CGRectMake(0, 64, WIDTH, HEIGHT - 64 - ChatHeight - 10 );
        self.sendMsgView.frame = CGRectMake(0, HEIGHT - ChatHeight , WIDTH, ChatHeight);
        [textView resignFirstResponder];
    }else
    {
        NSLog(@"%@",textView.text);
    }
}
- (float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    UITextView *detailTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, width, 0)];
    detailTextView.font = [UIFont systemFontOfSize:fontSize];
    detailTextView.text = value;
    CGSize deSize = [detailTextView sizeThatFits:CGSizeMake(width,CGFLOAT_MAX)];
    return deSize.height;
}
#pragma mark - 键盘位置的变化
-(void)handleKeyBoardDidShow:(NSNotification *)paramNotification
{
    CGSize size = [[paramNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    _sendBackViewHeight = size.height;
    
    [UIView animateWithDuration:0.000001 animations:^{
        self.tableView.frame = CGRectMake(0, 64, WIDTH, HEIGHT - 64 - ChatHeight - size.height);
        self.sendMsgView.frame = CGRectMake(0, HEIGHT - ChatHeight - size.height, WIDTH, ChatHeight);
        
    }];
}
-(void)handleKeyboardWillHide:(NSNotification *)paramNotification
{
    [UIView animateWithDuration:0.1 animations:^{
        if(_sendTextViewHeight > 0)
        {
            self.tableView.frame = CGRectMake(0, 64, WIDTH, HEIGHT - 64 - _sendTextViewHeight + 10 );
            self.sendMsgView.frame = CGRectMake(0, HEIGHT - _sendTextViewHeight  - 10, WIDTH, _sendTextViewHeight + 10);
        }
        else
        {
            self.tableView.frame = CGRectMake(0, 64, WIDTH, HEIGHT - 64 - ChatHeight - 10 );
            self.sendMsgView.frame = CGRectMake(0, HEIGHT - ChatHeight , WIDTH, ChatHeight);
        }
     }];
}

#pragma mark - 发送聊天消息
- (void)sendMsgsWithText:(NSString *)text bodyType:(NSString *)bodyType
{
    XMPPMessage *msg = [XMPPMessage messageWithType:@"chat" to:self.friendjid];
    //    text :纯文本
    //    image 图片
    //    video：语音
    [msg addAttributeWithName:@"bodyType" stringValue:bodyType];
    //    设置内容
    [msg addBody:text];
    NSLog(@"%@",msg);
    [[ONEChatXMPPTool sharedONEChatXMPPTool].xmppStream sendElement:msg];
}
# pragma mark - 消息滚动到底部
- (void)scrollToTableBottom
{
    NSInteger lastRow = _resultContr.fetchedObjects.count - 1;
    if (lastRow < 0 ) {
        return;
    }
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:lastRow inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastPath atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
}
@end
